import { effect, reactive } from '@feng3d/reactivity';

export interface Todo {
    readonly id: number;
    readonly text: string;
    readonly completed: boolean;
}

export class App {
    readonly currentTime: string = '';
    readonly isDarkMode: boolean = false;
    readonly count: number = 0;
    readonly step: number = 1;
    readonly initialValue: number = 10;
    readonly name: string = '世界';
    readonly todos: readonly Todo[] = [
        { id: 1, text: '学习Svelte', completed: false },
        { id: 2, text: '创建示例项目', completed: true },
        { id: 3, text: '掌握TypeScript', completed: false }
    ];
    readonly completedTodos: number = 0;
    readonly totalTodos: number = 0;
    readonly progress: number = 0;

    init() {
        const r_this = reactive(this);
        const updateTime = (): void => {
            r_this.currentTime = new Date().toLocaleTimeString('zh-CN');
        }

        updateTime();
        const interval = setInterval(updateTime, 1000);

        //
        effect(() => {
            r_this.completedTodos = r_this.todos.filter(todo => todo.completed).length;
        });

        effect(() => {
            r_this.totalTodos = r_this.todos.length;
        });

        effect(() => {
            r_this.progress = r_this.totalTodos > 0 ? (r_this.completedTodos / r_this.totalTodos) * 100 : 0;
        });

        effect(() => {
            document.body.classList.toggle("dark-mode", r_this.isDarkMode);
        });

        effect(() => {
            r_this.count = r_this.initialValue;
        });

        return () => clearInterval(interval);
    }

    addTodo(): void {
        const newTodo: Todo = {
            id: Date.now(),
            text: `新任务 ${this.totalTodos + 1}`,
            completed: false
        };

        reactive(this.todos).push(newTodo);
    }

    removeTodo(id: number): void {
        const index = this.todos.findIndex(todo => todo.id === id);

        if (index !== -1) {
            reactive(this.todos).splice(index, 1);
        }
    }

    toggleTodo(id: number): void {
        const todo = this.todos.filter(todo => todo.id === id)[0];

        if (todo) {
            reactive(todo).completed = !todo.completed;
        }
    }

    toggleTheme(): void {
        reactive(this).isDarkMode = !this.isDarkMode;
    }

    incrementCount(): void {
        reactive(this).count = this.count + 1;
    }

    decrementCount(): void {
        reactive(this).count = this.count - 1;
    }

    resetCount(): void {
        reactive(this).count = this.initialValue;
    }
}

export const app = new App();
export const r_app = reactive(app);